
package com.compuvest.admin.chart.xml;

import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class ParserChart extends DefaultHandler {
    
    private ArrayList<ChartRecord> listUser;
    private String tempVal;
    private ChartRecord chart;

//
    public ParserChart() {
        listUser = new ArrayList<ChartRecord>();
    }

    public ArrayList<ChartRecord> getUserList() {
        return this.listUser;
    }

    //Event Handlers
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //reset
        tempVal = "";
        if(qName.equalsIgnoreCase("User")) {
            chart = new ChartRecord();
            chart.setUserName(attributes.getValue("name"));
            chart.setDate(attributes.getValue("date"));
        }
    }
	
	
//
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if(qName.equalsIgnoreCase("User")) {
            //add it to the list
            listUser.add(chart);
        }
        else if(qName.equalsIgnoreCase("days_30")) {
            chart.setDays30(strToDouble(tempVal));
        }
        else if(qName.equalsIgnoreCase("days_60")) {
            chart.setDays60(strToDouble(tempVal));
        }
        else if(qName.equalsIgnoreCase("days_90")) {
            chart.setDays90(strToDouble(tempVal));
        }
        else if(qName.equalsIgnoreCase("days_180")) {
            chart.setDays180(strToDouble(tempVal));
        }
        else if(qName.equalsIgnoreCase("days_240")) {
            chart.setDays240(strToDouble(tempVal));
        }
        else if(qName.equalsIgnoreCase("days_more")) {
            chart.setDaysMore(strToDouble(tempVal));
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
	tempVal = new String(ch,start,length);
    }

//
    private double strToDouble(String str) {
        double value;
        try {
            value = Double.valueOf(str);
        } 
        catch (NumberFormatException e1) {
            value = 0d;
        }
        return value;
    }
}
